import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
} from '@nestjs/common';
import { Response } from 'express';

// @Catch(HttpException) 表示这个过滤器捕获所有HttpException及其子类
@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    // 获取请求上下文
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();

    // 获取异常状态码和响应体
    const status = exception.getStatus();
    const exceptionResponse = exception.getResponse();

    // 统一异常响应格式
    response.status(status).json({
      success: false,
      data: null,
      // 异常消息
      message:
        typeof exceptionResponse === 'object'
          ? (exceptionResponse as any).message || exception.message
          : exceptionResponse || exception.message,
      statusCode: status,
    });
  }
}
